#include "kvstore.h"

// 需要实现五种：iocp(windows)  reactor  ntyco  uring  kqueue 
#define KVSTORE_MAX_TOKENS 128  
const char *commands[] = {
    "SET", "GET", "DEL", "MOD",
};

enum
{
    KVS_CMD_START = 0,
    KVS_CMD_SET = KVS_CMD_START,
    KVS_CMD_GET,
    KVS_CMD_DEL,
    KVS_CMD_MOD,
    KVS_CMD_COUNT = KVS_CMD_MOD,
};

void *kvstore_malloc(size_t size){
    return malloc(size);
}
void kvstore_free(void *ptr){
    return free(ptr);
}

int kvstore_split_token(char *msg, char **tokens){
    if(msg == NULL || tokens == NULL)return -1;

    int idx = 0;
    char *token = strtok(msg, " ");

    while(token != NULL){
        tokens[idx ++] = token;
        token = strtok(NULL, " ");    //这个函数不是线程安全的
    }
    return idx;
}

// 为啥传入item
int kvstore_parse_protocol(struct conn_item *item, char **tokens, int count){
    if(item == NULL || tokens[0] == NULL || count == 0)return -1;

    int cmd = KVS_CMD_START;
    for(;cmd <= KVS_CMD_COUNT;cmd++){
        if(strcmp(commands[cmd],tokens[0]) == 0){
            break;
        }
    }

    char *msg = item->wbuffer;
    memset(msg, BUFFER_LENGTH, 0);
    switch (cmd)
    {
    case KVS_CMD_SET:
        {
        int res = kvstore_array_set(tokens[1], tokens[2]);
        if (!res){
            printf("success\n");
            snprintf(msg, BUFFER_LENGTH, "SUCCESS");
        }else{
            snprintf(msg, BUFFER_LENGTH, "SET FAILED");
        }
        break;
        }
    case KVS_CMD_GET:
        {
        char *value = kvstore_array_get(tokens[1]);
        if (value)
        {
            snprintf(msg, BUFFER_LENGTH, "%s", value);
        }else{
            snprintf(msg, BUFFER_LENGTH, "NO EXIST");
        }
        break;
        }
    case KVS_CMD_DEL:
        break;
    case KVS_CMD_MOD:
        break;
    default:
        assert(0);
    }
}

int kvstore_request(struct conn_item *item){
    char *msg = item->rbuffer;
    char *tokens[KVSTORE_MAX_TOKENS];

    int count = kvstore_split_token(msg, tokens);
    int idx = 0;
    for(;idx < count; idx ++){
        printf("idx: %s\n",tokens[idx]);
    }
    
    // 调用协议解析函数处理请求
    kvstore_parse_protocol(item, tokens, count);
    
    return 0;
}

int main(){
#if(ENABLE_NETWORK_SELECT == NETWORK_EPOLL)
    epoll_entry();
#elif(ENABLE_NETWORK_SELECT == NETWORK_NTYCO)
    ntyco_entry();
#elif(ENABLE_NETWORK_SELECT == NETWORK_IOURING)
    iouring_entry();
#endif
}